from typing import List, Optional


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        return self.reverseNode(None,head)

    def reverseNode(self, prev: Optional[ListNode], curr: Optional[ListNode]) -> Optional[ListNode]:
        if curr:
            # 储存下一个节点
            next = curr.next
            # 当前节点的下一个节点指向上一个节点
            curr.next = prev
            return self.reverseNode(curr, next)
        return prev


if __name__ == '__main__':
    node1 = ListNode(1)
    node2 = ListNode(2)
    node3 = ListNode(3)

    node1.next = node2
    node2.next = node3

    solution = Solution()
    node = solution.reverseList(node1)

    while node:
        print(node.val)
        node = node.next
